package com.gxuwz.jwt.interceptor;

import com.auth0.jwt.JWT;
import com.gxuwz.jwt.annotation.CheckToken;
import com.gxuwz.jwt.annotation.LoginToken;
import com.gxuwz.jwt.entity.User;
import com.gxuwz.jwt.service.UserService;
import com.gxuwz.jwt.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
        //获取http请求头的token
        String token = request.getHeader("token");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(LoginToken.class)) {
            LoginToken loginToken = method.getAnnotation(LoginToken.class);
            if (loginToken.required()) {
                return true;
            }
        }

        if (method.isAnnotationPresent(CheckToken.class)) {
            CheckToken checkToken = method.getAnnotation(CheckToken.class);
            if (checkToken.required()) {
                if (token == null) {
                    throw new RuntimeException("无token,请重新登陆");
                }
                String userId = JWT.decode(token).getClaim("userId").asString();
                User user = userService.getUserById(userId);
                if (user == null) {
                    throw new RuntimeException("用户不存在");
                }

                Boolean check = JwtUtil.checkJWT(token, user);
                System.out.println("check +++");
                if (!check) {
                    System.out.println("非法");
                    throw new RuntimeException("非法访问");
                }
                return true;
            }
        }
        return true;
    }
}
